package com.cloud.config;

import com.cloud.annotation.DesAnnotation;
import com.cloud.utils.DesensitizationUtil;
import com.cloud.utils.MD5Utils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

public class DesSerializer extends JsonSerializer<String> implements ContextualSerializer {

    private String rule;

    public DesSerializer() {
    }

    public DesSerializer(String rule) {
        this.rule = rule;
    }

    /**
     * 每次调用接口执行
     *
     * @param s
     * @param jsonGenerator
     * @param serializerProvider
     * @throws IOException
     */
    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

        if (StringUtils.isEmpty(rule)) {
            s = DesensitizationUtil.mobileEncrypt(s);
        }
        // 根据rule走不同的规则
        if ("1".equals(rule)) {
            s = MD5Utils.md5(s);
        }
        // 将修改后的值序列化到 JSON 中
        jsonGenerator.writeObject(s);
    }

    /**
     * 第一次启动时执行
     *
     * @param serializerProvider
     * @param beanProperty
     * @return
     * @throws JsonMappingException
     */
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            DesAnnotation t = beanProperty.getAnnotation(DesAnnotation.class);
            if (t != null) {
                AnnotatedMember member = beanProperty.getMember();
                if (member != null) {
//                    Class<?> parentClass = member.getDeclaringClass();
//                    String parentClassName = parentClass.getName();
//                    System.out.println("Parent Class Name: " + parentClassName);
////                    packages = parentClassName + "." + beanProperty.getName();
                    return new DesSerializer(t.rule());
                }
            }
        }
        return serializerProvider.findNullValueSerializer(beanProperty);
    }
}